package com.itheima.logdemo.utils;

import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LogUtil {
    private static final Logger logger = LoggerFactory.getLogger("kafka");
    private final static ThreadLocal<LogBean> logBeanThreadLocal = new ThreadLocal<>();
    
    public static void setLocalInstance(LogBean bean) {
        logBeanThreadLocal.set(bean);
    }
    
    public static LogBean getLocalInstance() {
        return logBeanThreadLocal.get();
    }
    
    public static void removeLocalInstance() {
        logBeanThreadLocal.remove();
    }
    
    /**
     * 常规链路追踪日志
     *
     * @param message
     */
    public static void log(String message) {
        LogBean bean = logBeanThreadLocal.get();
        if (bean == null) {
            throw new RuntimeException("Local Logbean not exist!");
        }
        bean.setMessage(message);
        logger.info(JSON.toJSONString(bean));
    }
    
    /**
     * 时间统计
     *
     * @param event 事件名称
     * @param time  花费时间
     */
    public static void cost(String event, long time) {
        LogBean bean = logBeanThreadLocal.get();
        if (bean == null) {
            throw new RuntimeException("Local Logbean not exist!");
        }
        bean.setMessage(event);
        bean.setTime(time);
        logger.info(JSON.toJSONString(bean));
        //打完日志后，抹掉时间信息，防止threadlocal往下传递
        bean.setTime(null);
    }
}
